package com.dingwei.lesyndrome.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dingwei.lesyndrome.R;
import com.dingwei.lesyndrome.adapter.SelectedMerchantsAdapter;
import com.dingwei.lesyndrome.app.MyApplication;
import com.dingwei.lesyndrome.bean.SelectedMerchantsBean;
import com.dingwei.lesyndrome.mvp.presenter.SelectedMerchantsPresenter;
import com.dingwei.lesyndrome.mvp.view.Contract;
import com.dingwei.lesyndrome.weight.MyScrollView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.SpaceDecoration;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.DisplayUtil;
import com.lihao.baselibrary.utils.ScreenUtils;
import com.lihao.baselibrary.weight.MyRadioGroup;
import com.lihao.baselibrary.weight.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created time 2018/3/7.
 * Creator 南柯一梦丶 on
 * Personal signature 余生还长 何必慌张
 * Page description :
 */

public class SelectedMerchantsActivity extends BaseActivity implements Contract.SelectedMerchantsView {
    SelectedMerchantsPresenter selectedMerchantsPresenter = new SelectedMerchantsPresenter(this);
    @Bind(R.id.search_layout)
    LinearLayout searchLayout;
    @Bind(R.id.banner)
    MZBannerView banner;
    @Bind(R.id.tv_last)
    TextView tvLast;
    @Bind(R.id.line1)
    View line1;
    @Bind(R.id.last_layout)
    LinearLayout lastLayout;
    @Bind(R.id.tv_most)
    TextView tvMost;
    @Bind(R.id.line2)
    View line2;
    @Bind(R.id.most_layout)
    LinearLayout mostLayout;
    @Bind(R.id.m_recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.img_no_data)
    ImageView imgNoData;
    @Bind(R.id.tv_no_data)
    TextView tvNoData;
    @Bind(R.id.no_data_layout)
    RelativeLayout noDataLayout;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.no_net_btn)
    TextView noNetBtn;
    @Bind(R.id.no_net_layout)
    RelativeLayout noNetLayout;
    @Bind(R.id.title_bar)
    TitleBar titleBar;
    @Bind(R.id.data_layout)
    LinearLayout dataLayout;
    @Bind(R.id.tv_last_copy)
    TextView tvLastCopy;
    @Bind(R.id.line1_copy)
    View line1Copy;
    @Bind(R.id.last_layout_copy)
    LinearLayout lastLayoutCopy;
    @Bind(R.id.tv_most_copy)
    TextView tvMostCopy;
    @Bind(R.id.line2_copy)
    View line2Copy;
    @Bind(R.id.most_layout_copy)
    LinearLayout mostLayoutCopy;
    @Bind(R.id.ll_type_copy)
    LinearLayout llTypeCopy;
    @Bind(R.id.ll_type)
    LinearLayout llType;
    @Bind(R.id.scrollView)
    MyScrollView scrollView;
    SelectedMerchantsBean bean;

    private SelectedMerchantsAdapter adapter;
    private String id;
    private String orderby = "zxfb";//排序方式（非必传，默认zxfb；最新发布：zxfb，关注最多：gzzd）

    @Override
    protected int getContentViewId() {
        return R.layout.activity_selected_merchants;
    }

    @Override
    protected void initData() {
        selectedMerchantsPresenter.initData(id, orderby, page, true, true);
    }

    @Override
    protected void initView() {
        if (getIntent().hasExtra("title")){
            titleBar.setTitleText(getIntent().getStringExtra("title"));
        }
        id = getIntent().getStringExtra("id");


        banner.setIndicatorVisible(false);
        LinearLayout.LayoutParams lp = new MyRadioGroup.LayoutParams(ScreenUtils.getScreenWidth(BaseActivity.context), ScreenUtils.getScreenWidth(BaseActivity.context) / 16 * 6);
        banner.setLayoutParams(lp);


        adapter = new SelectedMerchantsAdapter(BaseActivity.context);
        GridLayoutManager layoutManager = new GridLayoutManager(BaseActivity.context, 2);
        layoutManager.setSpanSizeLookup(adapter.obtainGridSpanSizeLookUp(2));
        SpaceDecoration itemDecoration = new SpaceDecoration((int) DisplayUtil.dip2px(BaseActivity.context, 16));//参数是距离宽度
        itemDecoration.setPaddingEdgeSide(false);//是否为左右2边添加padding.默认true.
        itemDecoration.setPaddingStart(false);//是否在给第一行的item添加上padding(不包含header).默认true.
        itemDecoration.setPaddingHeaderFooter(false);//是否对Header于Footer有效,默认false.

        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addItemDecoration(itemDecoration);


        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page = page + 1;
                selectedMerchantsPresenter.initData(id, orderby, page, false, false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                selectedMerchantsPresenter.initData(id, orderby, page, true, false);
            }
        });

        scrollView.setOnMyTouchListener(new MyScrollView.MyOnTouchLisener() {
            @Override
            public void onMyTouchLisener(int y) {
                int[] type = new int[2];
                llType.getLocationInWindow(type);
                int[] typeCopy = new int[2];
                llTypeCopy.getLocationInWindow(typeCopy);

                //排序悬停
                if (type[1] < typeCopy[1] - 1) {
                    llTypeCopy.setVisibility(View.VISIBLE);
                    llType.setVisibility(View.INVISIBLE);
                } else if (type[1] > typeCopy[1] + 1) {
                    llTypeCopy.setVisibility(View.INVISIBLE);
                    llType.setVisibility(View.VISIBLE);
                }
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                SelectedMerchantsBean.DataBean.ListBean bean = adapter.getItem(position);
                intent = new Intent(BaseActivity.context,PeripheralDetailActivity.class);
                intent.putExtra("id",bean.id);
                startActivity(intent);
            }
        });

        titleBar.setOnMenuListener(new TitleBar.OnMenuListener() {
            @Override
            public void onMenuClick() {
                intent  = new Intent(BaseActivity.context,CheckPeripheralActivity.class);
                startActivityForResult(intent,0);
            }
        });

        banner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int i) {
                SelectedMerchantsBean.DataBean.ImgListBean imgListBean =  bean.data.imgList.get(i);
                if (imgListBean.type.equals("info")){
                    intent = new Intent(BaseActivity.context,PeripheralDetailActivity.class);
                    intent.putExtra("id",imgListBean.id);
                    startActivity(intent);
                }else {
                    intent = new Intent(BaseActivity.context,WebViewActivity.class);
                    intent.putExtra("url",imgListBean.url);
                    intent.putExtra("title","详情");
                    startActivity(intent);
                }

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.search_layout, R.id.last_layout, R.id.most_layout,R.id.last_layout_copy, R.id.most_layout_copy, R.id.no_net_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_layout:
                intent = new Intent(BaseActivity.context,PeripheralSearchActivity.class);
                startActivity(intent);
                break;
            case R.id.last_layout:
                tvLast.setTextColor(getResources().getColor(R.color.theme_color));
                line1.setBackgroundColor(getResources().getColor(R.color.theme_color));
                tvMost.setTextColor(getResources().getColor(R.color.text_color_gray));
                line2.setBackgroundColor(getResources().getColor(R.color.white));

                tvLastCopy.setTextColor(getResources().getColor(R.color.theme_color));
                line1Copy.setBackgroundColor(getResources().getColor(R.color.theme_color));
                tvMostCopy.setTextColor(getResources().getColor(R.color.text_color_gray));
                line2Copy.setBackgroundColor(getResources().getColor(R.color.white));

                orderby = "zxfb";
                page = 1;
                selectedMerchantsPresenter.initData(id, orderby, page, true, true);
                break;
            case R.id.most_layout:
                tvMost.setTextColor(getResources().getColor(R.color.theme_color));
                line2.setBackgroundColor(getResources().getColor(R.color.theme_color));
                tvLast.setTextColor(getResources().getColor(R.color.text_color_gray));
                line1.setBackgroundColor(getResources().getColor(R.color.white));

                tvMostCopy.setTextColor(getResources().getColor(R.color.theme_color));
                line2Copy.setBackgroundColor(getResources().getColor(R.color.theme_color));
                tvLastCopy.setTextColor(getResources().getColor(R.color.text_color_gray));
                line1Copy.setBackgroundColor(getResources().getColor(R.color.white));
                orderby = "gzzd";
                page = 1;
                selectedMerchantsPresenter.initData(id, orderby, page, true, true);
                break;
            case R.id.last_layout_copy:
                tvLast.setTextColor(getResources().getColor(R.color.theme_color));
                line1.setBackgroundColor(getResources().getColor(R.color.theme_color));
                tvMost.setTextColor(getResources().getColor(R.color.text_color_gray));
                line2.setBackgroundColor(getResources().getColor(R.color.white));

                tvLastCopy.setTextColor(getResources().getColor(R.color.theme_color));
                line1Copy.setBackgroundColor(getResources().getColor(R.color.theme_color));
                tvMostCopy.setTextColor(getResources().getColor(R.color.text_color_gray));
                line2Copy.setBackgroundColor(getResources().getColor(R.color.white));

                orderby = "zxfb";
                page = 1;
                selectedMerchantsPresenter.initData(id, orderby, page, true, true);
                break;
            case R.id.most_layout_copy:
                tvMost.setTextColor(getResources().getColor(R.color.theme_color));
                line2.setBackgroundColor(getResources().getColor(R.color.theme_color));
                tvLast.setTextColor(getResources().getColor(R.color.text_color_gray));
                line1.setBackgroundColor(getResources().getColor(R.color.white));

                tvMostCopy.setTextColor(getResources().getColor(R.color.theme_color));
                line2Copy.setBackgroundColor(getResources().getColor(R.color.theme_color));
                tvLastCopy.setTextColor(getResources().getColor(R.color.text_color_gray));
                line1Copy.setBackgroundColor(getResources().getColor(R.color.white));
                orderby = "gzzd";
                page = 1;
                selectedMerchantsPresenter.initData(id, orderby, page, true, true);
                break;
            case R.id.no_net_btn:
                page = 1;
                selectedMerchantsPresenter.initData(id, orderby, page, true, true);
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        banner.pause();//暂停轮播
    }

    @Override
    public void onResume() {
        super.onResume();
        banner.start();//开始轮播
    }

    @Override
    public void onFail() {
        showData("fail");
    }

    public void showData(String state) {
        if (state.equals("success")) {
            noNetLayout.setVisibility(View.GONE);
            dataLayout.setVisibility(View.VISIBLE);
            if (adapter.getAllData() != null && adapter.getAllData().size() > 0) {
                mRecyclerView.setVisibility(View.VISIBLE);
                noDataLayout.setVisibility(View.GONE);
            } else {
                mRecyclerView.setVisibility(View.GONE);
                noDataLayout.setVisibility(View.VISIBLE);
            }
        } else {
            dataLayout.setVisibility(View.GONE);
            noNetLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onLoadMore(SelectedMerchantsBean bean) {
        adapter.addAll(bean.data.list);
        refreshLayout.finishLoadmore();
        showData("success");
    }

    @Override
    public void onRefresh(SelectedMerchantsBean bean) {
        this.bean = bean;
        if (bean.data.imgList != null && bean.data.imgList.size() > 0) {
            banner.setIndicatorVisible(false);
            // 设置数据
            banner.setPages(bean.data.imgList, new MZHolderCreator<BannerViewHolder>() {
                @Override
                public BannerViewHolder createViewHolder() {
                    return new BannerViewHolder();
                }
            });
            banner.start();
            banner.setVisibility(View.VISIBLE);
        } else {
            banner.setVisibility(View.GONE);
        }

        adapter.clear();
        adapter.addAll(bean.data.list);
        refreshLayout.finishRefresh();
        showData("success");
    }

    public static class BannerViewHolder implements MZViewHolder<SelectedMerchantsBean.DataBean.ImgListBean> {
        private ImageView mImageView;
        private TextView tvTitle;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.item_news_banner, null);
            mImageView = (ImageView) view.findViewById(R.id.img);
            tvTitle = (TextView) view.findViewById(R.id.tv_title);
            tvTitle.setVisibility(View.GONE);
            return view;
        }

        @Override
        public void onBind(Context context, int position, SelectedMerchantsBean.DataBean.ImgListBean data) {
            // 数据绑定
            Glide.with(BaseActivity.context)
                    .load(data.img)
                    .apply(MyApplication.options_no_transform)
                    .into(mImageView);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0) {
                page = 1;
                id = data.getStringExtra("id");
                selectedMerchantsPresenter.initData(data.getStringExtra("id"),orderby,page,true,true);
                titleBar.setTitleText(data.getStringExtra("title"));
            }
        }

    }

}
